# -*- coding: utf-8 -*-

from odoo import models, fields, api
import urllib3
import json


class Task(models.Model):
    _name = 'beet_flowable.task'
    _rec_name = 'name'
    _description = 'task'

    p_id = fields.Char("流程id")
    name = fields.Char("任务名称")

    url = fields.Char("url")
    end_time = fields.Char("结束时间")

    finished = fields.Boolean("已结束", compute='_compute_is_finished')

    @api.depends('end_time')
    def _compute_is_finished(self):
        for record in self:
            record.finished = record.end_time and record.end_time != ''

    def do_approve(self):
        http = urllib3.PoolManager()
        headers = urllib3.util.make_headers(basic_auth='rest-admin:test')
        headers.update({'Content-Type': 'application/json'})

        URL = 'http://rest-admin:test@localhost:8080/flowable-rest/service/runtime/tasks/%s' % self.p_id

        data = {"action": "complete"}
        postdata = json.dumps(data).encode('utf-8')
        http.request('POST', URL, headers=headers, body=postdata)

    def do_reject(self):
        http = urllib3.PoolManager()
        headers = urllib3.util.make_headers(basic_auth='rest-admin:test')
        headers.update({'Content-Type': 'application/json'})

        URL = 'http://rest-admin:test@localhost:8080/flowable-rest/service/runtime/tasks/%s' % self.p_id

        data = {"action": "complete",
                "outcome": "rejected",
                "variables":[
                    {
                        "name": "outcome",
                        "type": "string",
                        "value": "rejected",
                    }
                ]
                }
        postdata = json.dumps(data).encode('utf-8')
        http.request('POST', URL, headers=headers, body=postdata)


class Process(models.Model):
    _name = 'beet_flowable.process'
    _rec_name = 'name'
    _description = 'process'

    p_id = fields.Char("流程id")
    name = fields.Char("流程名称")
    deploymentTime = fields.Datetime("部署时间")
    category = fields.Char("分类")
    url = fields.Char("url")
    tenantId = fields.Char("tenantId")

    def do_apply(self):
        http = urllib3.PoolManager()
        headers = urllib3.util.make_headers(basic_auth='rest-admin:test')
        headers.update({'Content-Type': 'application/json'})

        URL = 'http://rest-admin:test@localhost:8080/flowable-rest/service/runtime/process-instances'

        data = {"processDefinitionId": self.p_id,
                "name": "流程"}
        postdata = json.dumps(data).encode('utf-8')
        r = http.request('POST', URL, headers=headers, body=postdata)
        # if r.status == 200:
            # self.unlink()


class Node(models.Model):
    _name = 'beet_flowable.node'
    _rec_name = 'name'
    _description = 'node'

    name = fields.Char("name")


class History(models.Model):
    _name = 'beet_flowable.history'
    _rec_name = 'name'
    _description = 'history'

    name = fields.Char("name")
